<?php
declare (strict_types=1);

namespace addons\V2\admin\model;

use app\common\model\Base;

class Spec extends Base
{
    protected $name = 'addons_mall_spec';

    public function cate1()
    {
        return $this->hasOne(ProductCate::class, 'id', 'cate_1')->field('id,title');
    }


    public function item()
    {
        return $this->hasMany(SpecItem::class, 'spec_id');
    }


    public static function _save($param, $admin)
    {
        try {
            $param['value'] = implode(',', array_filter($param['value']));
            $item_id = [];
            if (isset($param['id']) && $param['id']) {
                $item_id = $param['item_id'];
                parent::update($param);
                $id = $param['id'];
            } else {
                $spec = parent::create($param);
                $id = $spec->id;
            }
            SpecItem::setSpec($id, $param['value'], $item_id);

            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    public static function getSpec($id, $key, $pid = '')
    {
        try {
            $that = parent::where([$key => $id, 'status' => 1, 'delete_time' => 0])->field('id,key,value');

            $list = $that->select();

            $sku = [];
            foreach ($list as $v) {
                $data['id'] = $v->id;
                $data['title'] = $v['key'];
                $data['child'] = [];
                $value = SpecItem::where('spec_id', $v->id)->select();
                foreach ($value as $item) {
                    $data['child'][] = [
                        'id'      => $item->id,
                        'title'   => $item['name'],
                        'checked' => false
                    ];
                }
                if ($pid) {
                    $data['child'] = self::getItemSpec($data['child'], $pid, $v->id);
                }
                $sku[] = $data;

            }

            $skuData = [];
            if ($pid) {
                $skuData = ProductSpecValue::getSpecValue($pid);
            }


            return ['code' => 1, 'msg' => 'success', 'result' => ['specData' => $sku, 'skuData' => $skuData]];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function getItemSpec($item, $pid, $spec_id, $business = '')
    {

        $specData = ProductSpecData::where(['pid' => $pid, 'spec_id' => $spec_id])->find();
        if ($specData) {
            $child = json_decode($specData['child'], true);

            foreach ($item as &$skuItem) {
                foreach ($child as $childItem) {
                    if ($childItem['id'] == $skuItem['id']) {
                        $skuItem['checked'] = $business ? 1 : true;
                    }
                }
            }

        }
        return $item;
    }


}
